import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login.vue'
import Register from '@/views/Register.vue'
import Detail from '@/views/Detail.vue'
import Article from '@/views/Article.vue'
import Like from '@/views/Like.vue'
import Collect from '@/views/Collect.vue'
import User from '@/views/User.vue'
import Layout from '@/views/Layout.vue'
import { Toast } from 'vant'
import { getToken } from '@/utils/storage'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    { path: '/register', component: Register },
    { path: '/article/:id', component: Detail },

    {
      path: '/',
      component: Layout,
      redirect: '/article',

      children: [
        { path: 'article', component: Article },
        { path: 'like', component: Like },
        { path: 'collect', component: Collect },
        { path: 'user', component: User }
      ]
    }

  ]
})

// 前置导航守卫: 特定时机 自动执行
// 跳转前

const whiteList = ['/login', '/register']
router.beforeEach((to, from, next) => {
  // 产品经理告诉你, 游客只能看登录和注册
  // 如果用户已登录 - 直接放行
  // 如果用户未登录 - 去login register - 也要放行
  next()
  const token = getToken()
  if (token) {
    next()
  } else if (whiteList.includes(to.path)) {
    next()
  } else {
    // 如果用户未登录 - 去article user collect like 文章详情 - 不放行
    Toast('请先登录 再访问')
    next('/login')
  }
})

export default router
